package com.scs.application.core.security;

import com.scs.application.core.utils.WebUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
public class WebSessionManager extends DefaultWebSessionManager {

    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {

        return getAccessToken((HttpServletRequest) request);
    }

    public static String getAccessToken(HttpServletRequest request) {
        // 先从cookie获取
        Cookie[] cookies = request.getCookies();
        if(cookies != null){
            for (Cookie cookie : cookies) {
                if(cookie.getName().equalsIgnoreCase(WebUtils.AUTHORIZATION_HEADER)){
                    return cookie.getValue();
                }
            }
        }

        //从header中获取token
        String token = request.getHeader(WebUtils.AUTHORIZATION_HEADER);

        //如果header中不存在token，则从参数中获取token
        if (StringUtils.isBlank(token)) {
            token = request.getParameter(WebUtils.AUTHORIZATION_HEADER);
        }


        return token;
    }
}
